﻿using UnityEngine;
using System.Collections;
//using BlGame.Effect;

using TTGame;

/*
 * EffectScript
 *
 *
 * 依赖：
 * 不依赖于其他类
 *
 * ！不写重复代码！
 * @author TTun
 * @date 7/12/2017 5:16:56 PM
 */
namespace TTGameEngine {

public class EffectScript : MonoBehaviour {
    /// <summary>
    /// 特效生命周期
    /// </summary>
    public float lifeTime = 2.0f;
    [HideInInspector]
    public float curentLifeTime;
    public bool unUseLifeTime = false;

    private bool deactive = false;
    private bool isRecycle = true;
    private Transform[] childs;
    private Transform recordParent;
    private int recordLayer = -1;

    void OnEnable() {
        if(lifeTime < 0f) {
            lifeTime = 1f;
        }
        curentLifeTime = lifeTime;
        deactive = false;
    }

    void OnDisabele() {
        //绑在对象身上的提前消失
        OnDeactive();
    }

    // Update is called once per frame
    void Update() {
        if(!unUseLifeTime) {
            curentLifeTime -= Time.deltaTime;
            if(curentLifeTime < 0f) {
                OnDeactive();
            }
        }
    }

    public void OnDeactive() {
        if(deactive) { return; }
        deactive = true;
        curentLifeTime = -1f;
        if(isRecycle) {
            if(recordLayer > 0) {
                SetLayer(recordLayer);
                recordLayer = -1;
            }
            if(recordParent) {
                transform.SetParent(recordParent);
                recordParent = null;
            }
            ObjectRecycler.instance.Deactivate(gameObject);
        } else { Destroy(gameObject); }
    }

    public void SetParent(Transform form, Vector3 offset) {
        if(form == null) {
            return;
        }
        recordParent = transform.parent;
        transform.SetParent(form);
        transform.localPosition = offset;
    }

    public void SetRecycle(bool flag) {
        isRecycle = flag;
    }

    public void SetLayer(int layer) {
        if(childs == null) {
            childs = GetComponentsInChildren<Transform>();
            recordLayer = gameObject.layer;
        }
        foreach(Transform temp in childs) {
            temp.gameObject.layer = layer;
        }
    }


}


}